﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Xml;

public partial class View_Image : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            string checkCode = CreateRandomCode(4);
            Session["CheckCode"] = checkCode;
            CreateImage(checkCode);
        }
    }
    /**-----------------------------生成验证码------------------------------------**/
    public string CreateRandomCode(int codeCount)
    {
        string allChar = "2,3,4,5,6,7,8,9,0,1";
        string[] allCharArray = allChar.Split(',');
        string randomCode = "";

        Random rand = new Random((int)DateTime.Now.Ticks);
        for (int i = 0; i < codeCount; i++)
        {

            int t = rand.Next(allCharArray.Length);
            randomCode += allCharArray[t];
        }
        return randomCode;
    }
    public void CreateImage(string checkCode)
    {
        int iwidth = (int)(checkCode.Length * 10);
        //生成图的宽
        Bitmap image = new Bitmap(iwidth, 20);
        //生成图
        Graphics g = Graphics.FromImage(image);
        //建立处理对象
        //一种更改背景色的方法
        g.Clear(Color.FromArgb(255, 255, 255, 255));
        //更改背景色
        g.DrawString(checkCode, new Font("Arial", 12, FontStyle.Bold), new SolidBrush(Color.Coral), new PointF(2, 4));
        //绘文字


        Pen blackPen = new Pen(Color.FromArgb(255, 255, 0, 150));
        Random rand = new Random();
        for (int i = 0; i < 15; i++)
        {
            int y = rand.Next(image.Height);
            int x = rand.Next(image.Width);
            g.DrawLine(blackPen, x, y, x, y - 1);
        }

        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
        Response.ClearContent();
        Response.ContentType = "image/Jpeg";
        Response.BinaryWrite(ms.ToArray());

        g.Dispose();
        image.Dispose();
        Response.End();
    }
}
